#pragma once
#include"Socket.hpp"
#include "Protocol.hpp"
#include<functional>
using func_t =std::function<std::string( std::string&)>;
class TcpServer
{
    public:
    TcpServer(const uint16_t &port,func_t callback)
    :port_(port),call_back(callback)
    {

    }
    void Init()
    {
        listen_fd.Socket();
        listen_fd.Bind(port_);
        listen_fd.Listen();
        lg(DEBUG,"Initialize Server success!!");
    }
    void Start()
    {
        std::string inbuffer_stream;
        while(true)
        {
            std::string peerip;
            uint16_t peerport;
           int newfd= listen_fd.Accept(&peerip,&peerport);
           if(newfd<0)continue;
           //提供服务
           if(fork()==0)
           {
            //child
            listen_fd.Close();

            while(true)
            {
                //读
                char buffer[4096];
              ssize_t n=  read(newfd,buffer,sizeof(buffer));
              if(n>0)
              {
                buffer[n]=0;
                inbuffer_stream+=buffer;
                while(true)
              {
                std::string info=call_back(inbuffer_stream);//这里每读到一个完整的报文就会删掉一个
                if(info.empty())break;
                write(newfd,info.c_str(),info.size());
              }
              }
              else if(n==0)break;
              else break;
            }


            exit(0);
           }
           close(newfd);
        }
    }
    ~TcpServer()
    {

    }

    private:
    uint16_t port_;
    Sock listen_fd;
    func_t call_back;
};